<template>
  <ul class="list">
    <li
      class="item"
      v-for="item in letters"
      :key="item"
      :ref="item"
      @click="alphaClick"
      @touchstart.prevent="moveStart"
      @touchmove="myMove"
      @touchend="moveEnd"
    >{{item}}</li>
  </ul>
</template>

<script>
export default {
  name: 'city-alphabet',
  props: {
    cities: Object
  },
  data () {
    return {
      touchStatus: false,
      startY: 0,
      timer: null
    }
  },
  computed: {
    letters () {
      let letters = []
      for (let item in this.cities) {
        letters.push(item)
      }
      return letters
    }
  },
  methods: {
    alphaClick (e) {
      this.$emit('change', e.target.innerHTML)
    },
    moveStart () {
      this.touchStatus = true
    },
    myMove (e) {
      if (this.touchStatus) {
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          let itemY = e.touches[0].clientY - 79
          let index = Math.floor((itemY - this.startY) / 20)
          if (index >= 0 && index < this.letters.length) {
            this.$emit('change', this.letters[index])
          }
        }, 16)
      }
    },
    moveEnd () {
      this.touchStatus = false
    }
  },
  updated () {
    this.startY = this.$refs['A'][0].offsetTop
  }
}
</script>

<style lang="stylus" scoped>
@import '~styles/varibles.styl'
  .list
    z-index 1
    display flex
    flex-direction column
    justify-content center
    position absolute
    top 1.58rem
    right 0
    bottom 0
    width .4rem
    .item
      line-height .4rem
      text-align center
      color $bgColor
</style>
